package com.kzw.oa.system.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.kzw.core.Constants;
import com.kzw.core.bean.Msg;
import com.kzw.core.bean.OnlineUser;
import com.kzw.core.mapper.Jackson;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.BeanUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.StringUtil;
import com.kzw.core.util.json.JSON;
import com.kzw.core.util.web.ResponseUtils;
import com.kzw.misc.utils.AppUtil;
import com.kzw.misc.utils.ContextUtil;
import com.kzw.oa.system.model.AppRole;
import com.kzw.oa.system.model.AppUser;
import com.kzw.oa.system.model.Department;
import com.kzw.oa.system.model.UserOrg;
import com.kzw.oa.system.service.AppRoleService;
import com.kzw.oa.system.service.AppUserService;
import com.kzw.oa.system.service.DepartmentService;
import com.kzw.oa.system.service.UserOrgService;

@Controller
@RequestMapping("/system/user")
public class AppUserAction {

	private static Long SUPPER_ADMIN_ID = 1L; // 超级管理员角色ID
	
	@Autowired
	private DepartmentService organizationService;
	@Autowired
	private UserOrgService userOrgService;

	@Autowired
	private AppUserService appUserService;
	@Autowired
	private AppRoleService appRoleService;

	
	/**
	 * 测试tree部门
	 */
	@RequestMapping("treeTest")
	public void treeTest(HttpServletResponse response) {
		String json = appUserService.getCurUserInfo();
		ResponseUtils.renderJson(response, json);
	}
	/**
	 * 显示当前用户,并且加载该用户的所有权限
	 */
	@RequestMapping("getCurrent")
	public void getCurrent(HttpServletResponse response) {
		String json = appUserService.getCurUserInfo();
		ResponseUtils.renderJson(response, json);
	}
	
	/**
	 * 获取用户信息
	 */
	@RequestMapping("info")
	public void info(HttpServletRequest request, HttpServletResponse response) {
		AppUser currentUser = ContextUtil.getCurrentUser();
		String json = Jackson.me().with(Department.class, "depId", "depName")
				.with(AppRole.class, "roleId","roleName").without(AppUser.class, "orgs","topModules","rights","password").toJson(currentUser);
		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 列出所有账号(不列出超级管理员)
	 */
	@RequestMapping("list")
	public void list(HttpServletRequest request, HttpServletResponse response) {
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		filters.add(new StringPropertyFilter("EQI_delFlag", Constants.FLAG_UNDELETED.toString()));
		// 不显示超级管理员
		filters.add(new StringPropertyFilter("GTL_userId", "1"));

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		if (pageRequest.getOrderBy() == null) {
			pageRequest.setOrderBy("orgSn,userSn,userId");
			pageRequest.setOrderDir("asc,asc,asc");
		}

		Page<AppUser> page = appUserService.search2(pageRequest, filters);

		String json = new JSON(page).buildWithFilters(3, "appUsers", "userOrgs", "orgs", "roles", "authorities",
				"password", "positions", "topModules", "rights", "demension", "company");

		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 根据部门查找列表
	 */
	// @RequestMapping("select")
	// public String select(HttpServletRequest request, HttpServletResponse
	// response) {
	// // 是否根据角色查询翻页
	// String roleId = request.getParameter("roleId");
	// if (StringUtils.isNotEmpty(roleId)) {
	// return find();
	// }
	// // 是否根据查询条件再翻页查询
	// String fullname = request.getParameter("Q_fullname_S_LK");
	// if (StringUtils.isNotEmpty(fullname)) {
	// return list(); //条件查询
	// }
	// PagingBean pb = getInitPagingBean();
	// String strDepId = getRequest().getParameter("depId");
	// // 表示从上级目录开始进行查找
	// String path = "0.";
	// appUser = ContextUtil.getCurrentUser();
	// if (StringUtils.isNotEmpty(strDepId)) {
	// Long depId = Long.parseLong(strDepId);
	// Department dep = departmentService.get(depId);
	// if (dep != null) {
	// path = dep.getPath();
	// }
	// } else {
	// Department dep = appUser.getDepartment();
	// if (dep != null) {
	// path = dep.getPath();
	// }
	// }
	//
	// List<AppUser> list = appUserService.findByDepartment(path, pb);
	// StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
	// .append(pb.getTotalItems()).append(",result:");
	//
	// Type type = new TypeToken<List<AppUser>>() {}.getType();
	// Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
	// .setDateFormat("yyyy-MM-dd").create();
	//
	// buff.append(gson.toJson(list, type));
	// buff.append("}");
	//
	// jsonString = buff.toString();
	// return SUCCESS;
	// }

	/**
	 * 在线用户
	 */
	@RequestMapping("online")
	public void online(Long depId, Long roleId, HttpServletResponse response) {
		Map<String, OnlineUser> onlineUsers = new HashMap<String, OnlineUser>();
		Map<String, OnlineUser> onlineUsersByDep = new HashMap<String, OnlineUser>();
		Map<String, OnlineUser> onlineUsersByRole = new HashMap<String, OnlineUser>();

		onlineUsers = AppUtil.getOnlineUsers();// 获得所有在线用户

		// 按部门选择在线用户
		if (depId != null) {
			for (String sessionId : onlineUsers.keySet()) {
				OnlineUser onlineUser = new OnlineUser();
				onlineUser = onlineUsers.get(sessionId);
				// if(onlineUser.getDepId().equals(depId)){
				String path = "";
				if (!onlineUser.getUserId().equals(AppUser.SUPER_USER)) {
					path = onlineUser.getDepPath();
				}
				if (!depId.equals(new Long(0))) {
					if (java.util.regex.Pattern.compile("." + depId + ".").matcher(path).find()) {
						onlineUsersByDep.put(sessionId, onlineUser);
					}
				} else {
					onlineUsersByDep.put(sessionId, onlineUser);
				}
			}
		}

		// 按角色选择在线用户
		if (roleId != null) {
			for (String sessionId : onlineUsers.keySet()) {
				OnlineUser onlineUser = new OnlineUser();
				onlineUser = onlineUsers.get(sessionId);
				if (java.util.regex.Pattern.compile("," + roleId + ",").matcher(onlineUser.getRoleIds()).find()) {
					onlineUsersByRole.put(sessionId, onlineUser);
				}
			}
		}

		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':").append(onlineUsers.size())
				.append(",result:");

		Jackson jackson = Jackson.me();
		if (depId != null) {
			buff.append(jackson.toJson(onlineUsersByDep.values()));
		} else if (roleId != null) {
			buff.append(jackson.toJson(onlineUsersByRole.values()));
		} else {
			buff.append(jackson.toJson(onlineUsers.values()));
		}
		buff.append("}");

		ResponseUtils.renderJson(response, buff.toString());
	}

	// /**
	// * 根据角色查询
	// */
	// @RequestMapping("find")
	// public String find() {
	// String strRoleId = getRequest().getParameter("roleId");
	// PagingBean pb = getInitPagingBean();
	// if (StringUtils.isNotEmpty(strRoleId)) {
	// List<AppUser> userList = appUserService.findByRole(Long
	// .parseLong(strRoleId), pb);
	// Type type = new TypeToken<List<AppUser>>() {
	// }.getType();
	// StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
	// .append(pb.getTotalItems()).append(",result:");
	// Gson gson = new GsonBuilder()
	// .excludeFieldsWithoutExposeAnnotation().create();
	// buff.append(gson.toJson(userList, type));
	// buff.append("}");
	//
	// jsonString = buff.toString();
	// } else {
	// jsonString = "{success:false}";
	// }
	// return SUCCESS;
	// }

	/**
	 * 批量删除
	 */
	@RequestMapping("multiDel")
	public void multiDel(String[] ids, HttpServletResponse response) {
		StringBuffer buff = new StringBuffer("{\"success\":true");
		if (ids != null) {
			buff.append(",\"msg\":\"");
			for (String id : ids) {
				AppUser delUser = appUserService.get(new Long(id));
				AppRole superAdmin = appRoleService.get(SUPPER_ADMIN_ID);
				if (delUser.getRoles().contains(superAdmin)) {
					buff.append("员工:").append(delUser.getUsername()).append("是超级管理员,不能删除!<br><br/>");
				} else if (delUser.getUserId().equals(ContextUtil.getCurrentUserId())) {
					buff.append("不能删除自己!<br></br>");
				} else {
					//delUser.setStatus(Constants.FLAG_DISABLE);
					delUser.setDelFlag(Constants.FLAG_DELETED);
					buff.append("成功删除");
					//delUser.setFullname("[" + delUser.getUsername() + "]");
					//delUser.setUsername("__" + delUser.getUsername());
					appUserService.saveOrUpdate(delUser);
				}
			}
			buff.append("\"");
		}
		buff.append("}");
		ResponseUtils.renderJson(response, buff.toString());
	}

	/**
	 * 显示详细信息
	 */
	@RequestMapping("get")
	public void get(Long userId, HttpServletResponse response) {
		AppUser appUser = null;
		if (userId != null) {
			appUser = appUserService.get(userId);
		} else {
			appUser = appUserService.get(ContextUtil.getCurrentUserId());
		} 
		// 将数据转成JSON格式
		StringBuffer sb = new StringBuffer("{success:true,totalCounts:1,data:[");
		String json = new JSON(appUser, true).buildWithFilters(2, "organization", "roles", "authorities", "password");
		sb.append(json);
		sb.append("]}");
		ResponseUtils.renderJson(response, sb.toString());
	}

	/**
	 * 查询已有角色
	 */
	@RequestMapping("selectedRoles")
	public void selectedRoles(Long userId, HttpServletResponse response) {
		if (userId != null) {
			AppUser appUser = appUserService.get(userId);
			Set<AppRole> roles = appUser.getRoles();
			StringBuffer sb = new StringBuffer("[");
			for (AppRole role : roles) {
				sb.append("['" + role.getRoleId() + "','" + role.getRoleName() + "'],");
			}
			sb.deleteCharAt(sb.length() - 1);
			sb.append("]");
			ResponseUtils.renderJson(response, sb.toString());
		}
	}

	/**
	 * 为某一用户提供可选的角色
	 */
	@RequestMapping("getRoles")
	public void getRoles(String userId, HttpServletResponse response) {

		List<AppRole> list = appRoleService.getAll();
		List<AppRole> allRole = new ArrayList<AppRole>();

		Set<AppRole> curRoles = new HashSet<AppRole>();
		if (StringUtils.isNotEmpty(userId)) {
			AppUser user = appUserService.get(new Long(userId));
			curRoles = user.getRoles();
		}
		for (AppRole role : list) {
			if (!curRoles.contains(role) && role.getStatus() != Constants.FLAG_DISABLE.shortValue()) {
				allRole.add(role);
			}
		}

		StringBuffer buff = new StringBuffer("{success:true,result:");
		buff.append(new JSON(allRole, true).buildWithFilters(2, "appUsers", "functions"));
		buff.append("}");

		ResponseUtils.renderJson(response, buff.toString());
	}

	/**
	 * 返回某一用户已有的角色
	 * 
	 * @return
	 */
	@RequestMapping("getSelRoles")
	public void getSelRoles(String userId, HttpServletResponse response) {

		if (StringUtils.isNotEmpty(userId)) {
			AppUser user = appUserService.get(new Long(userId));
			Set<AppRole> curRoles = user.getRoles();

			StringBuffer buff = new StringBuffer("{success:true,result:");
			buff.append(new JSON(curRoles, true).buildWithFilters(2, "appUsers", "functions"));
			buff.append("}");

			ResponseUtils.renderJson(response, buff.toString());
		}
	}

	//
	// /**
	// * 按职位查找所有用户 信息
	// */
	// public String posUsers() {
	// String posId = getRequest().getParameter("posId");
	// QueryFilter filter = new QueryFilter(getRequest());
	// if (StringUtils.isNotEmpty(posId) && !"0".equals(posId)) {
	// filter.addFilter("Q_positions.posId_L_EQ", posId.trim());
	// }
	//
	// filter
	// .addFilter("Q_delFlag_SN_EQ", Constants.FLAG_UNDELETED
	// .toString());
	//
	// List<AppUser> users = appUserService.getAll(filter);
	//
	// Type type = new TypeToken<List<AppUser>>() {
	// }.getType();
	// StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
	// .append(filter.getPagingBean().getTotalItems()).append(
	// ",result:");
	// // Gson gson = new
	// // GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
	// // buff.append(gson.toJson(users, type));
	// JSONSerializer serializer = new JSONSerializer();
	// serializer.transform(new DateTransformer("yyyy-MM-dd"),
	// new String[] { "accessionTime" });
	// buff.append(serializer.exclude(new String[] { "password" }).serialize(
	// users));
	// buff.append("}");
	// jsonString = buff.toString();
	// return SUCCESS;
	// }
	//
	// /**
	// * 查询可选角色
	// */
	// public String chooseRoles() {
	// List<AppRole> chooseRoles = appRoleService.getAll();
	// if (userId != null) {
	// setAppUser(appUserService.get(userId));
	// Set<AppRole> selectedRoles = appUser.getRoles();
	// for (AppRole role : selectedRoles) {
	// chooseRoles.remove(role);
	// }
	// }
	// StringBuffer sb = new StringBuffer("[");
	// for (AppRole role : chooseRoles) {
	// if (role.getStatus() != 0) {
	// sb.append("['" + role.getRoleId() + "','" + role.getRoleName()
	// + "'],");
	// }
	// }
	// sb.deleteCharAt(sb.length() - 1);
	// sb.append("]");
	// setJsonString(sb.toString());
	// return SUCCESS;
	// }

	/**
	 * 修改密码
	 */
	@RequestMapping("resetPassword")
	@ResponseBody
	public Msg resetPassword(String userId, String oldPassword, String password, String repassword) {
		oldPassword = StringUtil.encryptSha256(oldPassword);
		Msg msg = new Msg();
		AppUser appUser;
		if (StringUtils.isNotEmpty(userId)) {
			appUser = appUserService.get(new Long(userId));
		} else {
			appUser = ContextUtil.getCurrentUser();
		}

		boolean pass = false;
		if (oldPassword.equals(appUser.getPassword())) {
			if (password.equals(repassword)) {
				pass = true;
			} else {
				msg.setMsg("两次输入密码不一致.");
			}
		} else {
			msg.setMsg("旧密码输入不正确.");
		}
		if (pass) {
			appUser.setPassword(StringUtil.encryptSha256(password));
			appUserService.saveOrUpdate(appUser);
			msg.setSuccess(true);
		} else {
			msg.setSuccess(false);
		}
		return msg;
	}

	/**
	 * 重置密码 wzl
	 */
	@RequestMapping("savePwd")
	@ResponseBody
	public Msg createPassword(String userId, String newpassword, String password) {
		AppUser appUser;
		Msg msg = new Msg();
		if (StringUtils.isNotEmpty(userId)) {
			appUser = appUserService.get(new Long(userId));
		} else {
			appUser = ContextUtil.getCurrentUser();
		}

		if (newpassword.equals(password)) {
			appUser.setPassword(StringUtil.encryptSha256(newpassword));
			appUserService.saveOrUpdate(appUser);
		} else {
			msg.setMsg("重置失败!,两次输入的密码不一致,请重新输入!.");
			msg.setSuccess(false);
		}
		return msg;
	}

	/**
	 * 删除用户照片
	 */ 
	@RequestMapping("photo")
	@ResponseBody
	public Msg photo(Long userId) {
		AppUser appUser = appUserService.get(userId);
		appUser.setPhoto("");
		appUserService.saveOrUpdate(appUser);
		return new Msg(true);
	}

	//
	// /**
	// * 按部门查找合适做下属的用户
	// */
	// public String subAdepartment() {
	// PagingBean pb = getInitPagingBean();
	// String strDepId = getRequest().getParameter("depId");
	// String path = "0.";
	// AppUser user = ContextUtil.getCurrentUser();
	// if (StringUtils.isNotEmpty(strDepId)) {
	// Long depId = Long.parseLong(strDepId);
	// Department dep = departmentService.get(depId);
	// if (dep != null) {
	// path = dep.getPath();
	// }
	// } else {
	// Department dep = user.getDepartment();
	// if (dep != null) {
	// path = dep.getPath();
	// }
	// }
	// if ("0.".equals(path)) {
	// path = null;
	// }
	// Long uId = user.getUserId();
	//
	// // Set<Long> userIds = userSubService.findAllUpUser(uId);
	// // List<Long> userIdsL = userSubService.subUsers(uId);
	//
	// // userIds.add(uId);
	// // for (Long l : userIdsL) {
	// // userIds.add(l);
	// // }
	//
	// List<AppUser> list = appUserService.findSubAppUser(path, new HashSet(),
	// pb);
	// Type type = new TypeToken<List<AppUser>>() {
	// }.getType();
	// StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
	// .append(pb.getTotalItems()).append(",result:");
	// Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
	// .create();
	// buff.append(gson.toJson(list, type));
	// buff.append("}");
	// jsonString = buff.toString();
	// return SUCCESS;
	// }
	//
	// /**
	// * 根据角色来选择合适做下属的用户
	// */
	// public String subArole() {
	// String strRoleId = getRequest().getParameter("roleId");
	// PagingBean pb = getInitPagingBean();
	// AppUser user = ContextUtil.getCurrentUser();
	// if (StringUtils.isNotEmpty(strRoleId)) {
	// Long uId = user.getUserId();
	// // Set<Long> userIds = userSubService.findAllUpUser(uId);
	// // List<Long> userIdsL = userSubService.subUsers(uId);
	// // userIds.add(uId);
	// // for (Long l : userIdsL) {
	// // userIds.add(l);
	// // }
	// // List<AppUser> userList = appUserService.findSubAppUserByRole(
	// // new Long(strRoleId), userIds, pb);
	// // List<AppUser>
	// // userList=appUserService.findByRole(Long.parseLong(strRoleId),
	// // pb);
	// Type type = new TypeToken<List<AppUser>>() {
	// }.getType();
	// StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
	// .append(pb.getTotalItems()).append(",result:");
	// Gson gson = new GsonBuilder()
	// .excludeFieldsWithoutExposeAnnotation().create();
	// buff.append(gson.toJson(new ArrayList(), type));
	// buff.append("}");
	// jsonString = buff.toString();
	// } else {
	// jsonString = "{success:false}";
	// }
	// return SUCCESS;
	// }
	//
	// /**
	// * 按在线查找合适当下属的用户
	// */
	// public String onlineAsub() {
	// Map<String, OnlineUser> onlineUsers = new HashMap<String, OnlineUser>();
	// Map<String, OnlineUser> onlineUsersBySub = new HashMap<String,
	// OnlineUser>();
	// onlineUsers = AppUtil.getOnlineUsers();// 获得所有在线用户
	// // 按在线用户
	// AppUser user = ContextUtil.getCurrentUser();
	// Long uId = user.getUserId();
	// Set<Long> userIds = new HashSet();// userSubService.findAllUpUser(uId);
	// userIds.add(uId);
	// List<Long> userIdsL = new ArrayList();// userSubService.subUsers(uId);
	// for (Long l : userIdsL) {
	// userIds.add(l);
	// }
	// for (String sessionId : onlineUsers.keySet()) {
	// OnlineUser onlineUser = new OnlineUser();
	// onlineUser = onlineUsers.get(sessionId);
	// if (!userIds.contains(onlineUser.getUserId())) {
	// onlineUsersBySub.put(sessionId, onlineUser);
	// }
	// }
	// Type type = new TypeToken<java.util.Collection<OnlineUser>>() {
	// }.getType();
	// StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
	// .append(onlineUsers.size()).append(",result:");
	// Gson gson = new Gson();
	// buff.append(gson.toJson(onlineUsersBySub.values(), type));
	// buff.append("}");
	// jsonString = buff.toString();
	// return SUCCESS;
	// }
	//
	// /**
	// * 上属
	// */
	// public String upUser() {
	// Set<AppUser> set = relativeUserService.getUpUser(ContextUtil
	// .getCurrentUserId());
	//
	// StringBuffer buff = new StringBuffer("[");
	// for (Iterator it = set.iterator(); it.hasNext();) {
	// AppUser user = (AppUser) it.next();
	// buff.append("['" + user.getUserId().toString() + "','"
	// + user.getFullname() + "'],");
	// }
	// if (set.size() > 0) {
	// buff.deleteCharAt(buff.length() - 1);
	// }
	// buff.append("]");
	// setJsonString(buff.toString());
	// return SUCCESS;
	// }

	/**
	 * 当前用户修改个人资料
	 */
	@RequestMapping("profile")
	@ResponseBody
	public Msg profile(AppUser appUser) {

		AppUser curAppUser = ContextUtil.getCurrentUser();
		AppUser orgAppUser = appUserService.get(curAppUser.getUserId());

		try {
			BeanUtil.copyNotNullProperties(orgAppUser, appUser);
			appUserService.saveOrUpdate(orgAppUser);
			// 使其不需要重新登录都能正常显示已经修改过的用户名
			curAppUser.setFullname(orgAppUser.getFullname());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Msg(true);
	}

	// public String bindDyPwd() {
	// StringBuffer msg = new StringBuffer("{success:true,msg:'");
	// String curDynamicPwd = getRequest().getParameter("curDynamicPwd");
	// HashMap<String, String> input = new HashMap<String, String>();
	// input.put("app", "demoauthapp");
	// input.put("user", appUser.getDynamicPwd());
	// input.put("pw", curDynamicPwd);
	//
	// String result = appUserService.initDynamicPwd(input, "bind");
	//
	// if (result.equals("ok")) {
	// AppUser orgUser = appUserService.get(appUser.getUserId());
	// orgUser.setDynamicPwd(appUser.getDynamicPwd());
	// orgUser.setDyPwdStatus(AppUser.DYNPWD_STATUS_BIND);
	// appUserService.save(orgUser);
	// msg.append("成功绑定!");
	// } else {
	// msg.append(result);
	// }
	// msg.append("'}");
	// setJsonString(msg.toString());
	// return SUCCESS;
	// }
	//
	// public String unbindDyPwd() {
	// StringBuffer msg = new StringBuffer("{success:true,msg:'");
	// String curDynamicPwd = getRequest().getParameter("curDynamicPwd");
	// HashMap<String, String> input = new HashMap<String, String>();
	// input.put("app", "demoauthapp");
	// input.put("user", appUser.getDynamicPwd());
	// input.put("pw", curDynamicPwd);
	//
	// String result = appUserService.initDynamicPwd(input, "unbind");
	//
	// if (result.equals("ok")) {
	// AppUser orgUser = appUserService.get(appUser.getUserId());
	// orgUser.setDyPwdStatus(AppUser.DYNPWD_STATUS_UNBIND);
	// appUserService.save(orgUser);
	// msg.append("解绑成功!");
	// } else {
	// msg.append(result);
	// }
	// msg.append("'}");
	// setJsonString(msg.toString());
	// return SUCCESS;
	// }

	/**
	 * 针对对话框的用户选择及条件过滤 按角色查找失败？？
	 */
	@RequestMapping("dialog")
	public void dialog(HttpServletRequest request, HttpServletResponse response) {
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);

		// 是否为显示当前部门的员工
		String curDep = request.getParameter("cuDep");
		if (StringUtils.isNotEmpty(curDep)) {
			AppUser curUser = ContextUtil.getCurrentUser();
			filters.add(new StringPropertyFilter("EQL_organization.orgId", curUser.getDept().getDepId() + ""));
		}
		// 显示非删除的用户
		filters.add(new StringPropertyFilter("EQH_delFlag", "0"));
		pageRequest.setOrderBy("orgSn,userSn");
		pageRequest.setOrderDir("asc,asc");

		Page<AppUser> page = appUserService.search2(pageRequest, filters);

		String json = new JSON(page).buildWithFilters(3, "userOrgs", "organization", "orgs", "roles", "authorities",
				"password", "topModules", "rights", "demension");

		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 保存并更新用户信息
	 */
	@RequestMapping("save")
	@ResponseBody
	public Msg saveOrUpdate(AppUser newAppUser, HttpServletRequest request, HttpServletResponse response) {
		AppUser appUser = newAppUser;
		System.out.println("======================"+appUser.getFullname()+"=============================");

		if (newAppUser.getUserId() != null) {
			// 修改
			appUser = appUserService.get(newAppUser.getUserId());
			try {
				// 复制值
				BeanUtil.copyNotNullProperties(appUser, newAppUser);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// 新增
			AppUser au = appUserService.findUniqueBy("username", appUser.getUsername());
			if (au != null) {
				return new Msg(false, 1, "该用户已存在");
			}
			appUser.setPassword(StringUtil.encryptSha256(appUser.getPassword()));
			appUser.setDelFlag(Constants.FLAG_UNDELETED);

		}
		// 判断是否是同一个对象
		appUserService.saveOrUpdate(appUser);

		// 处理其对应的部门，用户等
		String roleIds = request.getParameter("roleIds");
		String orgIds = request.getParameter("orgIds");
		System.out.println("roleIds:" + roleIds + ", orgIds:" + orgIds);

		if (StringUtils.isNotEmpty(roleIds)) {
			String[] roleIdArr = roleIds.split("[,]");
			// 处理该用户对应的角色
			if (roleIdArr != null) {
				Set<AppRole> roles = new HashSet<AppRole>();
				for (String roleId : roleIdArr) {
					AppRole role = appRoleService.get(new Long(roleId));
					roles.add(role);
				}
				appUser.setRoles(roles);
				appUserService.saveOrUpdate(appUser);
			}
		}

		Gson gson = new Gson();
		if (StringUtils.isNotEmpty(orgIds)) {
			// 处理orgIds
			UserOrg[] uos = (UserOrg[]) gson.fromJson(orgIds, UserOrg[].class);
			if (uos != null) {
				for (UserOrg uo : uos) {
					uo.setAppUser(appUser);
					Department dept = organizationService.get(uo.getOrgId());
					if (uo.getIsPrimary() == UserOrg.PRIMARY) {
						// 设置主部门
						appUser.setDept(dept);
						appUser.setOrgSn(dept.getSn());
						appUserService.saveOrUpdate(appUser);
					}
					uo.setDept(dept);
					userOrgService.saveOrUpdate(uo);
				}
			}
		}
		return new Msg(true);
	}

	/**
	 * 加载表单实体 
	 */
	@RequestMapping("load")
	public void load(Long userId, HttpServletResponse response) {
		AppUser appUser = appUserService.get(userId);
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(new JSON(appUser, true).buildWithFilters(1));
		sb.append("}");
		ResponseUtils.renderJson(response, sb.toString());
	}

	/**
	 * 删除选择择的角色
	 */
	@RequestMapping("delRole")
	@ResponseBody
	public Msg delRole(Long userId, String roleId) {
		if (StringUtils.isNotEmpty(roleId)) {
			AppUser appUser = appUserService.get(userId);
			AppRole appRole = appRoleService.get(new Long(roleId));
			appUser.getRoles().remove(appRole);
			appUserService.saveOrUpdate(appUser);
		}
		return new Msg(true);
	}

	/**
	 * 取得某个部门下的所有用户，不取子部门用户
	 */
	@RequestMapping("depUsers")
	public void depUsers(String depId, HttpServletRequest request, HttpServletResponse response) {
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		String username = request.getParameter("Q_LKS_username");
		String fullname = request.getParameter("Q_LKS_fullname");

		Department org = null;
		if (StringUtils.isNotEmpty(depId) && !"0".equals(depId)) {
			org = organizationService.get(new Long(depId));
		}
		String orgPath = (org == null) ? "0." : org.getPath();

		Map<String, String> map = new HashMap<String, String>();
		map.put("username", username == null ? "" : username);
		map.put("fullname", fullname == null ? "" : fullname);
		Page<AppUser> page = appUserService.getDepUsers(orgPath, pageRequest, map);

		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':").append(page.getCount())
				.append(",result:[ ");
		Gson gson = new Gson();
		for (AppUser au : page.getData()) {
			buff.append("{");
			buff.append("\"userId\":").append("\"" + au.getUserId() + "\",");
			buff.append("\"username\":").append(gson.toJson(au.getUsername()) + ",");
			buff.append("\"fullname\":").append(gson.toJson(au.getFullname()) + ",");
			if (au.getEmail() != null) {
				buff.append("\"email\":").append(gson.toJson(au.getEmail()) + ",");
			}
			if (au.getUserSn() != null) {
				buff.append("\"userSn\":").append(gson.toJson(au.getUserSn()) + ",");
			}
			buff.append("\"depNames\":").append(gson.toJson(au.getDept().getDepName()) + ",");
			buff.append("\"roleNames\":").append(gson.toJson(au.getRoleNames()) + ",");
			buff.append("\"accessionTime\":").append(gson.toJson(au.getAccessionTime().toString().substring(0, 10)));
			buff.append("},");
		}
		String json = buff.toString().substring(0, buff.length() - 1) + "]}";
		ResponseUtils.renderJson(response, json);
	}
	
	/**
	 * iframe页面
	 */
	@RequestMapping("html/add")
	public String addUi() {
		return "system/user_form";
	}
	
	@RequestMapping("html/changePwd")
	public String changePwd(String userId,Model model) {
		model.addAttribute("userId",userId);
		return "system/user_changePwd";
	}
	/**
	 * 角色编辑
	 * @author wzl
	 */
	@RequestMapping("html/edit")
	public String editUi(Long userId, Model model) {
		AppUser user = appUserService.get(userId);
		//查找所需的角色
		StringBuffer roleIds = new StringBuffer("[");
		Set<AppRole> roles = user.getRoles();
		int flag = 0;
		for(AppRole i:roles) {
			if(flag==0) {
				roleIds.append("\""+i.getId()+"\"");
			}else {
				roleIds.append(",\""+i.getId()+"\"");
			}
			flag++;
		}
		roleIds.append("]");
		model.addAttribute("user", user);
		model.addAttribute("roleIds", roleIds+"");
		return "system/user_form";
	}

}
